<style>
    .layui-upload-list {
        margin: 10px 0 0 0
    }
    .layui-upload-list dd {
        position: relative;
        margin: 0 10px 10px 0;
        float: left
    }
    .layui-upload-list .item_img {
        width: 92px;
        height: 92px;
    }
    .layui-upload-list .operate {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 1;
        display: none;
    }
    /*.layui-upload-list:hover .operate {
        display:block;
    }*/
    .layui-upload-list .operate i {
        cursor: pointer;
        background: #2F4056;
        padding: 2px;
        line-height: 15px;
        text-align: center;
        color: #fff;
        margin-left: 1px;
        float: left;
        filter: alpha(opacity=80);
        -moz-opacity: .8;
        -khtml-opacity: .8;
        opacity: .8
    }
    .layui-upload-list dd .img {
        width: 92px;height: 92px;margin: 0 10px 10px 0;
    }
</style>
<div class="layui-fluid" lay-title="表单组合">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="" lay-filter="form-group" id="itemParamAddTable">
                <div class="layui-form-item">
                    <label class="layui-form-label">标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="itemTitle" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">品牌名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="brandTitle" lay-verify="required" autocomplete="off" placeholder="请输入品牌名称" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div id="catId">

                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">现价</label>
                    <div class="layui-input-block">
                        <input type="text" name="prePrice" lay-verify="required|price" autocomplete="off" placeholder="请输入现价" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">原价</label>
                    <div class="layui-input-block">
                        <input type="text" name="origPrice" lay-verify="required|price" autocomplete="off" placeholder="请输入原价" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">数量</label>
                    <div class="layui-input-block">
                        <input type="text" name="num" lay-verify="required|number" autocomplete="off" placeholder="请输入数量" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">图片</label>
                    <div class="layui-input-block " >
                        <div class="layui-upload">
                            <button class="layui-btn layui-btn-primary" type="button" id="editimg">上传图片</button >
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                预览图：
                                <div class="layui-upload-list" id="demo2"></div>
                            </blockquote>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">规格参数</label>
                    <div class="layui-input-block " >
                        <a href="javascript:void(0)" class="addGroup">
                            <i class="layui-icon">&#xe608;</i> 添加
                        </a>
                        <ul id="params">

                        </ul>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">规格</label>
                    <div class="layui-input-block">
                        <a href="javascript:void(0)" id="showParams">
                            <i class="layui-icon">&#xe608;</i>编辑
                        </a>
                        <table class="layui-table show-params" style="display: none">
                            <thead>
                                <tr>
                                    <th >标题</th>
                                    <th >价格</th>
                                    <th >库存</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>

                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">排序</label>
                    <div class="layui-input-block">
                        <input type="text" name="orderNum" lay-verify="required" autocomplete="off" placeholder="请输入排序" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">有效</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="1" title="有效" checked="">
                        <input type="radio" name="status" value="0" title="无效">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit="" lay-filter="form-group-submit">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="itemParamAddTemplate" style="display: none;">
    <li class="param">
        <ul>
            <li>
                <div class="layui-inline">
                    <input type="text" class="layui-input" autocomplete="off" style="width: 250px;" name="group"/>
                </div>
                <a href="javascript:void(0)" class="addParam">
                    <i class="layui-icon">&#xe654;</i>
                    <span>添加</span>
                </a>
            </li>
            <li>
                <span>|-------</span>
                <div class="layui-inline">
                    <input type="text" class="layui-input" autocomplete="off" style="width: 250px;" name="param"/>
                </div>
                <a href="javascript:void(0)" class="delParam">
                    <i class="layui-icon">&#xe640;</i>
                    <span>删除</span>
                </a>
            </li>
        </ul>
    </li>
</div>

<script>
    layui.use(['jquery', 'admin', 'form','layer','selectN','upload'], function () {
        var $ = layui.jquery
            , layer = layui.layer
            , form = layui.form
            , selectN = layui.selectN
            , upload = layui.upload
            , admin = layui.admin;

        var id = POPUP_DATA.id;
        var table = POPUP_DATA.table;
        var item = {};
        form.render(null, 'form-group');

        form.verify({
            price: [/^(?:[1-9][0-9]*(?:\.[0-9]{1,2})?|0(?:\.[0-9]{1,2})?)$/, '只能输入数字，小数点后只能保留两位']
        });

        // 规格库存价格编辑
        $("#showParams").on("click",function () {
            // 查询数据
            var params = getParams();
            if (params == null || params.length == 0) {
                layer.msg("您未添加规格参数");
                return false;
            }
            var prePrice = $("input[name=prePrice]").val();
            var num = $("input[name=num]").val();
            var str='';
            var specs = getItemSpecs(params);
            for (var i=0;i<specs.length;i++){
                var itemSpecs = specs[i];
                str+='<tr>\
                    <td>'+itemSpecs+'</td>\
                    <td>\
                    <input type="text" class="layui-input" name="price" value="'+prePrice+'">\
                    </td>\
                    <td >\
                    <input type="text" class="layui-input" name="stock" value="'+num+'">\
                    </td>\
                    </tr>';
            }
            $(".show-params tbody").html(str);
            $(".show-params").show();
        });

        var catId="";
        // 初始化
        if (id) {
            admin.get({
                type: 'get',
                url: '/item/info/' + id,
                dataType: 'json',
                async:false,
                success: function (data) {
                    item = data.item;
                    if (item) {
                        form.val("form-group", {
                            "itemTitle": item.title // "name": "value"
                            , "brandTitle": item.brandTitle
                            , "prePrice": item.prePrice
                            , "origPrice": item.origPrice
                            , "num": item.num
                            , "status": item.status
                            , "orderNum": item.orderNum
                        });
                        catId = item.catId;
                        // 预览图片
                        var images = item.image;
                        if(images != null && images != ""){
                            var imageArr = images.split(",");
                            if(imageArr != null && imageArr.length > 0){
                                for(var i=0;i<imageArr.length;i++){
                                    if(imageArr[i] != null && imageArr[i] != ""){
                                        // $('#demo2').append('<img style="width: 92px;height: 92px;margin: 0 10px 10px 0;" src="'+ imageArr[i] +'" class="layui-upload-img">')
                                        $('#demo2').append('<dd class="item_img" ><div class="operate"><i class="close layui-icon"></i></div><img src="' + imageArr[i] + '" class="img" ></dd>');
                                    }
                                }
                            }

                        }
                    }
                    var itemSpecsList = data.itemSpecsList;
                    if (itemSpecsList != null && itemSpecsList.length > 0) {
                        var str = '';
                        for (var i=0;i<itemSpecsList.length;i++) {
                            var itemSpecs = itemSpecsList[i];
                            str+='<tr>\
                                <td>'+itemSpecs.paramData+'</td>\
                                <td>\
                                <input type="text" class="layui-input" name="price" value="'+itemSpecs.price+'">\
                                </td>\
                                <td >\
                                <input type="text" class="layui-input" name="stock" value="'+itemSpecs.stock+'">\
                                </td>\
                                </tr>';
                        }
                        $(".show-params tbody").html(str);
                        $(".show-params").show();
                    }
                    var itemParamList = data.itemParamList;
                    if (itemParamList != null && itemParamList.length > 0) {
                        var str = '';
                        for (var i=0;i<itemParamList.length;i++) {
                            var itemParam = itemParamList[i];
                            var params = itemParam.params;
                            str+='<li class="param">\
                                <ul>\
                                <li>\
                                <div class="layui-inline">\
                                <input type="text" class="layui-input" autocomplete="off" value="'+itemParam.group+'" style="width: 250px;" name="group"/>\
                                </div>\
                                <a href="javascript:void(0)" class="addParam">\
                                <i class="layui-icon">&#xe654;</i>\
                            <span>添加</span>\
                            </a>\
                            </li>';

                            for (var j=0;j<params.length;j++) {
                                str+='<li>\
                                <span>|-------</span>\
                                <div class="layui-inline">\
                                    <input type="text" class="layui-input" autocomplete="off" value="'+params[j]+'" style="width: 250px;" name="param"/>\
                                    </div>\
                                    <a href="javascript:void(0)" class="delParam">\
                                    <i class="layui-icon">&#xe640;</i>\
                                <span>删除</span>\
                                </a>\
                                </li>';
                            }
                            str +='</ul>\
                             </li>';
                        }
                        $("#params").html(str);
                    }
                }
            });
        }
        // 下拉框赋值
        var typeSelect = null;
        admin.get({
            type: 'get',
            url: '/itemCat/list',
            dataType: 'json',
            success: function(data){
                var selected = [];
                selected.push(catId);
                //多选标签-所有配置
                typeSelect = selectN({
                    //元素容器【必填】
                    elem: '#catId'
                    ,search:[false,true]
                    //候选数据【必填】
                    ,selected: selected
                    ,data: data.list
                    //,width:930
                    ,autoWidth:true
                    ,last:true
                    ,field:{idName:'id',titleName:'title'}
                });
            }
        });

        $("#itemParamAddTable").on("click",".addGroup", function(){
            var temple = $(".itemParamAddTemplate li").eq(0).clone();
            $("#params").append(temple);
        });

        $("#params").on("click",".addParam",function () {
            var li = $(".itemParamAddTemplate li").eq(2).clone();
            li.appendTo($(this).parent().parent());
        });

        $("#params").on("click",".delParam",function () {
            var length = $(this).parent().parent().find("li").length;
            if (length == 2){
                $(this).parent().parent().remove();
            } else {
                $(this).parent().remove();
            }
        });

        $(".layui-upload-list .item_img").each(function(){
            $(this).hover(function() {
                $(this).find(".operate").css('display', 'block');
            }, function() {
                $(this).find(".operate").css('display', 'none');
            });
        });
        $(".layui-upload-list").on("click",".operate",function(){
            $(this).parent().remove();
        });

        // 图片上传
        upload.render({
            elem: '#editimg'
            ,url: '/fileUpload'
            ,multiple: true
            ,field: 'myfiles'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                /*obj.preview(function(index, file, result){
                    $('#demo2').append('<img style="width: 92px;height: 92px;margin: 0 10px 10px 0;" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                });*/
            }
            ,done: function(res){
                //上传完毕
                if (res.code == 0) {
                    $('#demo2').append('<dd class="item_img" ><div class="operate"><i class="close layui-icon"></i></div><img src="' + res.data[0] + '" class="img" ></dd>');

                    $(".layui-upload-list .item_img").each(function(){
                        $(this).hover(function() {
                            $(this).find(".operate").css('display', 'block');
                        }, function() {
                            $(this).find(".operate").css('display', 'none');
                        });
                    });
                } else {
                    layer.msg(res.msg);
                }
            }
        });

        form.on('submit(form-group-submit)', function (data) {
            var params = getParams();
            // 获取table表格中的数值
            var specs =[];
            $(".show-params tbody tr").each(function () {
                var obj = {};
                var paramData = $(this).find("td:first").html();
                var price = $(this).find("input[name='price']").val();
                var stock = $(this).find("input[name='stock']").val();
                obj.paramData = paramData;
                obj.price = price;
                obj.stock = stock;
                specs.push(obj);
            });
            // 获取图片
            var imageArr = [];
            $(".layui-upload-list img").each(function () {
                var image = $(this).attr("src");
                imageArr.push(image)
            });
            var field = data.field;
            var itemData = {};
            var url = "/item/save";
            if (id) {
                url = "/item/update?_method=PUT";
                itemData.id = id;
            }
            console.log(JSON.stringify(specs));
            itemData.title = field.itemTitle;
            itemData.catId = field.catId;
            itemData.brandTitle = field.brandTitle;
            itemData.prePrice = field.prePrice;
            itemData.origPrice = field.origPrice;
            itemData.isParam = "1";
            itemData.paramData = JSON.stringify(params);
            itemData.num = field.num;
            itemData.orderNum = field.orderNum;
            itemData.status = field.status;
            itemData.itemSpecsJson = JSON.stringify(specs);
            itemData.image = imageArr.join(",");

            admin.post({
                url: url,
                contentType: "application/json",
                data: JSON.stringify(itemData),
                success: function (res) {
                    if (res.code == 0) {
                        // 提醒保存成功，关闭当前弹窗
                        layer.msg(res.msg);
                        layer.closeAll();
                        //刷新
                        table.reload('list-table-item', {
                            url: '/item/page?token=' + admin.loginToken,
                            page: {
                                curr: 1
                            }
                        })
                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
            return false;
        });

        function getParams(){
            var params = [];
            var groups = $("input[name=group]");
            groups.each(function(i,e){
                var p = $(e).parent().parent().parent().find("[name=param]");
                var _ps = [];
                p.each(function(_i,_e){
                    var _val = $(_e).val();
                    if($.trim(_val).length>0){
                        _ps.push(_val);
                    }
                });
                var _val = $(e).val();
                if($.trim(_val).length>0 && _ps.length > 0){
                    params.push({
                        "group":_val,
                        "params":_ps
                    });
                }
            });
            return params;
        }

        function getItemSpecs(params){
            // 生成笛卡尔积
            var title = [];
            var content = [];
            for (var i = 0; i < params.length; i++){
                title[i] = params[i].group;
                var p = params[i].params;
                content[i] = p;
            }
            var result = DescartesUtils.descartes(content);
            var resultNew = [];
            for (var i = 0; i < result.length; i++) {
                var str = "[";
                for (var k = 0; k < result[i].length; k++) {
                    if (k == 0) {
                        str += '{"' + title[k] + '":"' + result[i][k] + '"}';
                    } else {
                        str += ',{"' + title[k] + '":"' + result[i][k] + '"}';
                    }
                }
                str += "]";
                resultNew.push(str);
            }
            return resultNew;
        }
    });

    var DescartesUtils = {
        /**
         * 如果传入的参数只有一个数组，求笛卡尔积结果
         * @param arr1 一维数组
         * @returns {Array}
         */
        descartes1:function(arr1){
            // 返回结果，是一个二维数组
            var result = [];
            var i = 0;
            for (i = 0; i < arr1.length; i++) {
                var item1 = arr1[i];
                result.push([item1]);
            }
            return result;
        },

        /**
         * 如果传入的参数只有两个数组，求笛卡尔积结果
         * @param arr1 一维数组
         * @param arr2 一维数组
         * @returns {Array}
         */
        descartes2: function(arr1, arr2) {
            // 返回结果，是一个二维数组
            var result = [];
            var i = 0, j = 0;
            for (i = 0; i < arr1.length; i++) {
                var item1 = arr1[i];
                for (j = 0; j < arr2.length; j++) {
                    var item2 = arr2[j];
                    result.push([item1, item2]);
                }
            }
            return result;
        },

        /**
         *
         * @param arr2D 二维数组
         * @param arr1D 一维数组
         * @returns {Array}
         */
        descartes2DAnd1D: function(arr2D, arr1D) {
            var i = 0, j = 0;
            // 返回结果，是一个二维数组
            var result = [];

            for (i = 0; i < arr2D.length; i++) {
                var arrOf2D = arr2D[i];
                for (j = 0; j < arr1D.length; j++) {
                    var item1D = arr1D[j];
                    result.push(arrOf2D.concat(item1D));
                }
            }

            return result;
        },

        descartes3: function(list) {
            var listLength = list.length;
            var i = 0, j = 0;
            // 返回结果，是一个二维数组
            var result = [];
            // 为了便于观察，采用这种顺序
            var arr2D = DescartesUtils.descartes2(list[0], list[1]);
            for (i = 2; i < listLength; i++) {
                var arrOfList = list[i];
                arr2D = DescartesUtils.descartes2DAnd1D(arr2D, arrOfList);
            }
            return arr2D;
        },

        //笛卡儿积组合
        descartes: function(list) {
            if (!list) {
                return [];
            }
            if (list.length <= 0) {
                return [];
            }
            if (list.length == 1) {
                return DescartesUtils.descartes1(list[0]);
            }
            if (list.length == 2) {
                return DescartesUtils.descartes2(list[0], list[1]);
            }
            if (list.length >= 3) {
                return DescartesUtils.descartes3(list);
            }
        }

    };
</script>